import {AnnexData} from '@/api/myPerformance'
import {ddGetAuth, ddUploadFile} from '@/api/dd'
import useGlobalAPI from './useGlobalAPI'
import { computed, ref } from 'vue'

function useUploadFile() {
  const {store} = useGlobalAPI()
  const loginUser = computed(() => store.getters['dingding/ddUserInfo'])

  /**附件 */
  let fileList = ref<
    {
      uid: string // 文件唯一标识，建议设置为负数，防止和内部产生的 id 冲突
      name: string // 文件名
      status: 'uploading' | 'done' | 'error' | 'removed' // 状态有：uploading done error removed
    }[]
  >([])
  /**上传附件返回的信息 */
  let annexDataList = ref<AnnexData[]>([])

  async function customRequest(e: {data: File; file: {uid: string}}) {
    console.log(e)
    let res = await ddGetAuth({userDDId: loginUser.value.userId}).catch(err => {})
    if (!res) return
    let formData = new FormData()
    formData.append('file', e.data)
    formData.append('userDDId', loginUser.value.userId)
    ddUploadFile(formData)
      .then(res => {
        let currentFileIdx = fileList.value.findIndex(item => item.uid === e.file.uid)
        fileList.value[currentFileIdx].status = 'done'
        annexDataList.value[currentFileIdx] = {
          annexFileExtension: res.data.dentry.extension,
          annexFileId: res.data.dentry.id,
          annexFileName: res.data.dentry.name,
          annexFileSize: res.data.dentry.size,
          annexFileSpaceId: res.data.dentry.spaceId
        }
        console.log(fileList.value)
        console.log(annexDataList.value)
      })
      .catch(err => {
        let currentFileIdx = fileList.value.findIndex(item => item.uid === e.file.uid)
        fileList.value[currentFileIdx].status = 'error'
        console.log(fileList.value)
        console.log(annexDataList.value)
      })
  }
}

export default useUploadFile
